package com.cloud.wms.ui.sort.detach;

import android.content.Intent;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.annimon.stream.Stream;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.cloud.core.utils.NumberUtils;
import com.cloud.core.widget.decoration.GridItemDecoration;
import com.cloud.widget.ScanText;
import com.cloud.widget.utils.DensityUtils;
import com.cloud.wms.R;
import com.cloud.wms.base.BaseBarListActivity;
import com.cloud.wms.config.IntentKey;
import com.cloud.wms.ui.sort.contract.DetachContact;
import com.cloud.wms.ui.sort.entity.DetachBoxBean;
import com.cloud.wms.ui.sort.entity.DetachDetailBean;
import com.cloud.wms.ui.sort.presenter.DetachPresenter;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by FC on 2021/3/8.
 * Desc：
 */
public class DetachBindActivity extends BaseBarListActivity<DetachBoxBean, DetachPresenter> implements DetachContact.View {
    @BindView(R.id.scan_text)
    ScanText scanText;
    @BindView(R.id.tv_batch_code)
    TextView tvBatchCode;
    @BindView(R.id.ll_box_count)
    LinearLayout llBoxCount;
    @BindView(R.id.tv_box_count)
    TextView tvBoxCount;
    @BindView(R.id.btn_confirm_bind)
    TextView btnConfirmBind;
    private List<DetachDetailBean> detailBeanList;
    private List<Long> orderIDList = new ArrayList<>();//订单ID集合
    private List<Integer> commodityAmountList = new ArrayList<>();//每个订单的商品数量
    private ArrayList<DetachBoxBean> boxBeanList = new ArrayList<>();//订单已经绑定容器，获取每个订单绑定的容器信息
    private boolean isNeedBind;//是否需要绑定容器

    @Override
    protected String barTitle() {
        return "二次分拨";
    }

    @Override
    protected int getResId() {
        return R.layout.activity_sort_detach_bind;
    }

    @Override
    protected int getItemResId() {
        return R.layout.item_second_allocation_bind;
    }

    @Override
    protected void onScanHandle(String result, int resultCode) {
        super.onScanHandle(result, resultCode);
        scanText.addHistory(result);
        if (NumberUtils.getInteger(tvBoxCount.getText().toString()) <= mAdapter.getItemCount()) {
            info("当前已添加足够容器，如需修改删除后重试");
            return;
        }
        long count = Stream.of(mAdapter.getData())
                .filter(detachBoxBean -> result.equalsIgnoreCase(detachBoxBean.getContainerCode()))
                .count();

        if (count > 0) {
            info("扫描容器已被添加，请勿重复添加");
            return;
        }
        mPresenter.checkBox(result);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        initScanText(scanText);
        detailBeanList = (List<DetachDetailBean>) getIntent().getSerializableExtra(IntentKey.OBJECT_KEY);
        isNeedBind = detailBeanList.get(0).isNeedBind();
        tvBatchCode.setText(detailBeanList.get(0).getBatchCode());
        for (int i = 0; i < detailBeanList.size(); i++) {
            if (!orderIDList.contains(detailBeanList.get(i).getOrderID())) {
                orderIDList.add(detailBeanList.get(i).getOrderID());
                if (!TextUtils.isEmpty(detailBeanList.get(i).getContainerCode())) {
                    DetachBoxBean detachBoxBean = new DetachBoxBean();
                    detachBoxBean.setContainerID(detailBeanList.get(i).getContainerID());
                    detachBoxBean.setContainerCode(detailBeanList.get(i).getContainerCode());
                    boxBeanList.add(detachBoxBean);
                }
            }
        }
        tvBoxCount.setText(String.valueOf(orderIDList.size()));
        for (int i = 0; i < orderIDList.size(); i++) {
            int commodityAmount = 0;
            for (int j = 0; j < detailBeanList.size(); j++) {
                if (orderIDList.get(i) == detailBeanList.get(j).getOrderID()) {
                    commodityAmount = commodityAmount + detailBeanList.get(j).getAmount();
                }
            }
            commodityAmountList.add(commodityAmount);
        }

        if (boxBeanList.size() != 0) {
            info("当前波次已经绑定容器，请确认后开始分拨！");
            mAdapter.setNewInstance(boxBeanList);
            if (boxBeanList.size() == Integer.parseInt(tvBoxCount.getText().toString())) {
                btnConfirmBind.setText("开始分拨");
                btnConfirmBind.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    protected RecyclerView.LayoutManager getLayoutManager() {
        return new GridLayoutManager(this, 3);
    }

    @Override
    protected RecyclerView.ItemDecoration itemDecoration() {
        return GridItemDecoration.newBuilder().spanCount(3)
                .verticalDivider(null, DensityUtils.Dp2Px(this, 6), false)
                .build();
    }

    @Override
    protected void bindItemData(BaseViewHolder helper, DetachBoxBean item) {
        helper.setText(R.id.tv_amount, String.valueOf(commodityAmountList.get(helper.getAdapterPosition())))
                .setText(R.id.tv_container_code, item.getContainerCode())
                .setGone(R.id.tv_title, item.getContainerCode().length() > 8)
                .setText(R.id.tv_bind_order, (helper.getAdapterPosition() + 1) + "号");
    }

    @Override
    public void onSuccess(Message message) {
        super.onSuccess(message);
        switch (message.what) {
            case DetachPresenter.CHECK_BOX_SUCCESS:
                DetachBoxBean boxBean = (DetachBoxBean) message.obj;
                mAdapter.addData(boxBean);
                if (mAdapter.getItemCount() >= NumberUtils.getInteger(tvBoxCount.getText().toString())) {
                    btnConfirmBind.setVisibility(View.VISIBLE);
                } else {
                    btnConfirmBind.setVisibility(View.GONE);
                }
                break;
            case DetachPresenter.BATCH_BIND_BOX_SUCCESS:
                ArrayList<DetachBoxBean> boxBeanList = (ArrayList<DetachBoxBean>) message.obj;
                Intent intent = new Intent(this, DetachConfirmActivity.class);
                intent.putExtra(IntentKey.OBJECT_KEY, (Serializable) detailBeanList);
                intent.putExtra(IntentKey.LIST_KEY, boxBeanList);
                startActivity(intent);
                finish();
                break;
        }
    }

    @OnClick({R.id.btn_confirm_bind})
    public void onClick() {
        for (int i = 0; i < mAdapter.getData().size(); i++) {
            mAdapter.getItem(i).setOrderID(orderIDList.get(i));
        }
        if (isNeedBind)
            mPresenter.batchBindBox(String.valueOf(detailBeanList.get(0).getBatchID()), mAdapter.getData());
        else {
            Intent intent = new Intent(this, DetachConfirmActivity.class);
            intent.putExtra(IntentKey.OBJECT_KEY, (Serializable) detailBeanList);
            intent.putExtra(IntentKey.LIST_KEY, boxBeanList);
            startActivity(intent);
            finish();
        }
    }

    @Override
    protected void itemClickListener(BaseQuickAdapter<DetachBoxBean, BaseViewHolder> mAdapter, View view, int position) {
        if (boxBeanList.size() != 0) {
            error("订单已绑定容器，不可删除");
            return;
        }
        DetachBoxBean item = mAdapter.getItem(position);
        new MaterialAlertDialogBuilder(this)
                .setTitle("删除确认")
                .setMessage("是否删除容器:" + item.getContainerCode() + "？")
                .setPositiveButton("确认", (dialog, which) -> {
                    mAdapter.remove(item);
                    if (mAdapter.getItemCount() == NumberUtils.getInteger(tvBoxCount.getText().toString())) {
                        btnConfirmBind.setVisibility(View.VISIBLE);
                    } else {
                        btnConfirmBind.setVisibility(View.GONE);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @Override
    protected void setupComponent() {
        getActivityComponent().inject(this);
    }

}
